<template>
	<view class="container">
		<!-- 顶部切换栏 -->
		<view class="type-switch">
			<view class="switch-item" 
				v-for="(item,index) in topOptionList" 
				:key="index"
				:class="{'active': topOption === index}"
				@click="changeOption(index)"
			>
					<text>{{item.title}}</text>
			</view>
		</view>

		<!-- 分类选择区 -->
		<scroll-view class="category-list" scroll-y>
			<view class="category-grid" :class="{'income': topOption === 0}">
				<view class="category-item" 
					v-for="(item,index) in topOption === 1 ? zhichuTypeList : shouruTypeList" 
					:key="index"
					:class="{'selected': OptionType === item.text}"
					@click="addType(index)"
				>
					<view class="icon-wrap">
						<image :src="item.icon" mode="aspectFit"></image>
					</view>
					<text>{{item.text}}</text>
				</view>
				<!-- 添加自定义分类按钮 -->
				<view class="category-item add-category" @click="showAddCategory">
					<view class="icon-wrap">
						<image src="/static/add.png" mode="aspectFit"></image>
						</view>
					<text>添加</text>
					</view>
				</view>
			</scroll-view>

		<!-- 记账区域 -->
		<view class="input-section">
			<!-- 金额显示 -->
			<view class="amount-display">
				<text class="currency">¥</text>
				<input 
					class="amount-input"
					type="digit"
					v-model="count"
					@input="handleKeyboardInput"
					@keydown="handleKeyDown"
					@focus="handleFocus"
					@blur="handleBlur"
					@mousewheel.prevent
				/>
		</view>

			<!-- 备注输入 -->
			<view class="note-input">
				<image src="/static/revocation.png" mode="aspectFit"></image>
				<input 
					type="text" 
					v-model="Option.OptionNote" 
					placeholder="添加备注" 
					placeholder-style="color: #999;"
				/>
			</view>

			<!-- 日期选择 -->
			<view class="date-picker" @click="$refs.pickerDate.open()">
				<image src="/static/calendar.png" mode="aspectFit"></image>
				<text>{{strDate}}</text>
			</view>

			<!-- 数字键盘 -->
			<view class="keypad">
				<view class="keypad-row" v-for="(row, rowIndex) in CounterList" :key="rowIndex">
					<view 
						class="key-item" 
						v-for="(key, keyIndex) in row" 
						:key="keyIndex"
						:class="{
							'operator': ['plus', 'minus', 'enter'].includes(key.Id),
							'enter': key.Id === 'enter',
							'delete': key.Id === 'back',
							'date': key.Id === 'date'
						}"
						@click="Overmouse(rowIndex, keyIndex)"
					>
						<template v-if="key.Id === 'back'">
							<image src="/static/left.png" mode="aspectFit"></image>
						</template>
						<text v-else>{{key.show}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 日期选择弹窗 -->
		<uni-popup ref="pickerDate" type="bottom">
			<view class="popup-view">
				<view class="popup-view-header">
					<text class="popup-view-cancel" @click="pickerCancel">取消</text>
					<text class="popup-view-confirm" @click="pickerConfirm">确定</text>
				</view>
				<picker-view 
					v-if="visible"
					:indicator-style="indicatorStyle" 
					:value="selectDate"
					@change="bindChangeDate" 
					class="picker-view"
				>
					<picker-view-column>
						<view class="item" v-for="item in years" :key="item">{{item}}年</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="item in months" :key="item">{{item}}月</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="item in days" :key="item">{{item}}日</view>
					</picker-view-column>
				</picker-view>
			</view>
		</uni-popup>

		<!-- 添加分类弹窗 -->
		<uni-popup ref="addCategoryPopup" type="center">
			<view class="add-category-popup">
				<view class="popup-header">
					<text>添加自定义分类</text>
				</view>
				<view class="popup-content">
					<input 
						type="text" 
						v-model="newCategoryName" 
						placeholder="输入分类名称"
						class="category-input"
						maxlength="4"
					/>
					<view class="icon-grid">
						<view 
							class="icon-item" 
							v-for="(icon, index) in defaultIcons" 
							:key="index"
							:class="{'selected': selectedIconIndex === index}"
							@click="selectIcon(icon, index)"
						>
							<image :src="icon.url" mode="aspectFit"></image>
						</view>
					</view>
				</view>
				<view class="popup-footer">
					<button @click="$refs.addCategoryPopup.close()" class="cancel-btn">取消</button>
					<button @click="confirmAddCategory" class="confirm-btn" type="primary">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			const date = new Date()
			const years = []
			const year = date.getFullYear()
			const months = []
			const month = date.getMonth() + 1
			const days = []
			const day = date.getDate()
			
			// 生成年份数组
			for (let i = 2000; i <= date.getFullYear() + 30; i++) {
				years.push(i)
			}
			
			// 生成月份数组
			for (let i = 1; i <= 12; i++) {
				months.push(i)
			}
			
			// 生成天数数组
			for (let i = 1; i <= 31; i++) {
				days.push(i)
			}

			// 格式化日期显示
			const formatNum = num => num < 10 ? `0${num}` : num
			const formattedDate = `${formatNum(month)}.${formatNum(day)}`
			const strDate = `${month}-${day}`
			const currDate = `${year}-${month}-${day}`

			return {
				// 基础数据
				visible: true,
				indicatorStyle: `height: 50px;`,
				years,
				year,
				months,
				month,
				days,
				day,
				selectDate: [years.indexOf(year), month - 1, day - 1],
				tempDate: null,

				// 输入相关
				count: '0',
				Intcount: 0,
				isKeyboardFocused: false,
				lastInputType: null,
				inputLock: false,

				// 日期相关
				strDate,
				currDate,

				// 分类相关
				topOption: 0,
				topOptionstr: '收入',
				OptionType: null,
				mouseOver: '',

				// Option 对象
				Option: {
					topOption: 0,
					OptionType: null,
					OptionTypeicon: null,
					strDate: currDate,
						OptionNote: '',
					intCount: 0
				},

				// 分类列表
				topOptionList: [
					{ title: '收入', type: 0 },
					{ title: "支出", type: 1 }
				],

				// 支出分类
				zhichuTypeList: [
					{ text: "服饰", icon: '/static/zhichu/fs.png' },
					{ text: "购物", icon: '/static/zhichu/gwc.png' },
					{ text: "交通", icon: '/static/zhichu/gjc.png' },
					{ text: "咖啡", icon: '/static/zhichu/kf.png' },
					{ text: "零食", icon: '/static/zhichu/ls.png' },
					{ text: "美容", icon: '/static/zhichu/mr.png' },
					{ text: "日用品", icon: '/static/zhichu/zhij.png' },
					{ text: "食品", icon: '/static/zhichu/jitui.png' },
					{ text: "运动", icon: '/static/zhichu/bq.png' },
					{ text: "娱乐", icon: '/static/zhichu/yule.png' }
				],

				// 收入分类
				shouruTypeList: [
					{ text: "工资", icon: '/static/shouru/gz.png' },
					{ text: "股票", icon: '/static/shouru/gp.png' },
					{ text: "红包", icon: '/static/shouru/hb.png' },
					{ text: "奖金", icon: '/static/shouru/lx4.png' },
					{ text: "兼职", icon: '/static/shouru/zp.png' },
					{ text: "租金", icon: '/static/shouru/zpgl.png' }
				],

				// 键盘配置
				CounterList: [
					[
						{ Id: '1', show: '1' },
						{ Id: '2', show: '2' },
						{ Id: '3', show: '3' },
						{ Id: 'date', show: '日期' }
					],
					[
						{ Id: '4', show: '4' },
						{ Id: '5', show: '5' },
						{ Id: '6', show: '6' },
						{ Id: 'plus', show: '+' }
					],
					[
						{ Id: '7', show: '7' },
						{ Id: '8', show: '8' },
						{ Id: '9', show: '9' },
						{ Id: 'minus', show: '-' }
					],
					[
						{ Id: 'dot', show: '.' },
						{ Id: '0', show: '0' },
						{ Id: 'back', show: '', Img: '/static/left.png' },
						{ Id: 'enter', show: '确认' }
					]
				],

				// 自定义分类相关
				newCategoryName: '',
				newCategoryIcon: '',
				selectedIconIndex: -1,
				defaultIcons: [
					{ url: '/static/zhichu/fs.png', name: '服饰' },
					{ url: '/static/zhichu/gwc.png', name: '购物' },
					{ url: '/static/zhichu/gjc.png', name: '交通' },
					{ url: '/static/zhichu/kf.png', name: '咖啡' },
					{ url: '/static/zhichu/ls.png', name: '零食' },
					{ url: '/static/zhichu/mr.png', name: '美容' }
				],

				// 添加日期是否已选择的标记
				dateSelected: false
			}
		},
		methods: {
			messageToggle(type) {
				if (type == 0) {
					if (this.topOption == 0) {
						this.messageText = `收入不能为负数`
						this.$refs.message.open()
					} else {
						this.messageText = `支出不能为负数`
						this.$refs.message.open()
					}

				} else {
					if (this.Option.OptionType == null || this.Option.OptionTypeicon == null) {
						this.messageText = ` 必要选项未填，无法提交`
						this.$refs.message.open()
					} else {
						uni.showLoading({
							title: '加载中...'
						})
						uniCloud.callFunction({
							name: 'upLoadBill',
							data: this.Option
						}).then(res => {
							console.log(1)
							uni.hideLoading()
							uni.navigateBack()
						}).catch(error => {
							console.log(error)
						})
					}
				}
			},
			bindChangeDate(e) {
				const val = e.detail.value
				const year = this.years[val[0]]
				const month = this.months[val[1]]
				const day = this.days[val[2]]
				
				// 存储临时日期
				this.tempDate = {
					year,
					month,
					day,
					selectDate: val
				}
			},
			pickerCancel() {
				// 清除临时数据
				this.tempDate = null
				this.$refs.pickerDate.close()
			},
			pickerConfirm() {
				if (this.tempDate) {
					const { year, month, day, selectDate } = this.tempDate
					
					// 更新日期显示
					const formatNum = num => num < 10 ? `0${num}` : num
					this.CounterList[0][3].show = `${formatNum(month)}.${formatNum(day)}`
					
					// 更新日期数据
					this.year = year
					this.month = month
					this.day = day
					this.selectDate = selectDate
					this.strDate = `${month}-${day}`
					this.Option.strDate = `${year}-${formatNum(month)}-${formatNum(day)}`
					
					// 标记日期已选择
					this.dateSelected = true
					
					// 清除临时数据
					this.tempDate = null
				}
				
				this.$refs.pickerDate.close()
			},
			Overmouse(rowIndex, keyIndex) {
				const key = this.CounterList[rowIndex][keyIndex]
				
				switch(key.Id) {
					case 'date':
						// 打开日期选择器
						this.$refs.pickerDate.open()
						break
					case 'back':
						if (this.count.length > 0) {
							this.count = this.count.slice(0, -1)
							if (this.count === '') {
								this.count = '0'
							}
						}
						break
					case 'enter':
						this.submitBill()
						break
					case 'dot':
						if (!this.count.includes('.')) {
										this.count += '.'
									}
						break
					case 'plus':
					case 'minus':
						// 处理加减号
						break
					default:
						// 处理数字输入
						if (this.count === '0') {
							this.count = key.show
						} else {
							this.count += key.show
						}
						break
				}
			},
			changeOption(index) {
				// 更新选中状态
				this.topOption = index;
				this.topOptionstr = this.topOptionList[index].title;
				
				// 重置分类选择
				this.Option.OptionType = null;
				this.Option.OptionTypeicon = null;
				
				// 重置金额
				this.count = '0';
				this.Intcount = 0;
				
				// 更新 Option 对象
				this.Option = {
					...this.Option,
					topOption: index,
					intCount: 0
				};
			},
			addType(index) {
				const list = this.topOption === 0 ? this.shouruTypeList : this.zhichuTypeList;
				const item = list[index];
				
				this.OptionType = item.text;
				this.Option.OptionType = item.text;
				this.Option.OptionTypeicon = item.icon;
			},
			handleKeyboardInput(e) {
				if (this.inputLock) return;
				
				const value = e.target.value;
				// 如果是从数字键盘切换到键盘输入，重置状态
				if (this.lastInputType === 'keypad') {
					this.count = '';
					this.lastInputType = 'keyboard';
				}

				// 验证输入格式
				if (/^\d*\.?\d{0,2}$/.test(value)) {
					this.count = value || '0'; // 如果输入为空，显示0
				}
			},
			handleKeyDown(e) {
				if (this.inputLock) return;
				
				if (e.key === 'Backspace') {
					e.preventDefault();
					this.deleteNumber();
				}
			},
			deleteNumber() {
				if (this.inputLock) return;
				
				this.inputLock = true;
				if (this.count.length > 0) {
					this.count = this.count === '0' ? '0' : 
								this.count.length === 1 ? '0' : 
								this.count.slice(0, -1);
				}
				setTimeout(() => {
					this.inputLock = false;
				}, 100);
			},
			inputNumber(num) {
				if (this.inputLock) return;
				
				this.inputLock = true;
				if (this.count === '0') {
					this.count = num;
							} else {
					// 检查小数点后的位数
					const parts = this.count.split('.');
					if (parts.length > 1 && parts[1].length >= 2) {
						this.inputLock = false;
						return; // 如果小数点后已有两位，不再添加
					}
					this.count += num;
				}
				setTimeout(() => {
					this.inputLock = false;
				}, 100);
			},
			handleFocus() {
				this.isKeyboardFocused = true;
				// 重置输入状态
				this.lastInputType = 'keyboard';
				this.inputLock = false;
			},
			handleBlur() {
				this.isKeyboardFocused = false;
				this.inputLock = false;
				// 格式化金额
				if (this.count) {
					const num = parseFloat(this.count);
					if (!isNaN(num)) {
						this.count = num.toFixed(2);
					}
				}
			},
			submitBill() {
				// 检查日期是否已选择
				if (!this.dateSelected) {
					uni.showToast({
						title: '请选择日期',
						icon: 'none'
					})
					return
				}
				
				// 验证金额
				if (!this.count || parseFloat(this.count) === 0) {
					uni.showToast({
						title: '请输入金额',
						icon: 'none'
					});
					return;
				}
				
				// 验证分类
				if (!this.Option.OptionType) {
					uni.showToast({
						title: '请选择分类',
						icon: 'none'
					});
					return;
				}

				// 这里添加提交账单的逻辑
				console.log('提交账单', {
					amount: this.count,
					type: this.Option.OptionType,
					note: this.Option.OptionNote,
					date: this.strDate
				});
			},
			showAddCategory() {
				this.newCategoryName = '';
				this.newCategoryIcon = '';
				this.selectedIconIndex = -1;
				this.$refs.addCategoryPopup.open();
			},
			selectIcon(icon, index) {
				this.newCategoryIcon = icon.url;
				this.selectedIconIndex = index;
			},
			confirmAddCategory() {
				if (!this.newCategoryName.trim()) {
					uni.showToast({
						title: '请输入分类名称',
						icon: 'none'
					});
					return;
				}

				if (!this.newCategoryIcon) {
					uni.showToast({
						title: '请选择分类图标',
						icon: 'none'
					});
					return;
				}

				// 根据当前是收入还是支出，添加到对应的列表中
				const newCategory = {
					text: this.newCategoryName,
					icon: this.newCategoryIcon
				};

				if (this.topOption === 0) {
					this.shouruTypeList.push(newCategory);
				} else {
					this.zhichuTypeList.push(newCategory);
				}

				// 关闭弹窗并重置数据
				this.$refs.addCategoryPopup.close();
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				});
			},
			// 添加重置方法
			resetForm() {
				// 重置日期显示为"日期"
				this.CounterList[0][3].show = '日期'
				this.dateSelected = false
				
				// 重置其他数据
				this.count = '0'
				this.Option.OptionNote = ''
				this.Option.OptionType = null
				this.Option.OptionTypeicon = null
				this.OptionType = null
			}
		},
		// 添加页面显示钩子
		onShow() {
			// 每次打开页面时重置表单
			this.resetForm()
		}
	}
</script>

<style>
.container {
	min-height: 100vh;
	background: #f8f9fa;
}

/* 顶部切换栏样式 */
.type-switch {
		display: flex;
	justify-content: center;
	padding: 20rpx;
	background: #fff;
}

.switch-item {
	padding: 20rpx 60rpx;
	margin: 0 20rpx;
	border-radius: 30rpx;
	font-size: 28rpx;
	transition: all 0.3s;
}

.switch-item.active {
	background: linear-gradient(135deg, #7F7FD5, #86A8E7);
	color: #fff;
}

/* 分类选择区样式 */
.category-list {
	background: #fff;
	padding: 30rpx;
	margin-top: 20rpx;
	max-height: 400rpx;
}

.category-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 30rpx;
}

.category-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20rpx;
	border-radius: 16rpx;
	transition: all 0.3s;
}

.category-item.selected {
	background: rgba(127, 127, 213, 0.1);
}

.icon-wrap {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background: #f5f7fa;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 10rpx;
}

.icon-wrap image {
	width: 44rpx;
	height: 44rpx;
}

/* 记账区域样式 */
.input-section {
	background: #fff;
	margin-top: 20rpx;
	padding: 30rpx;
}

.amount-display {
	display: flex;
	align-items: center;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.currency {
	font-size: 40rpx;
	color: #333;
	margin-right: 10rpx;
}

.amount-input {
	font-size: 60rpx;
	font-weight: 500;
	flex: 1;
	border: none;
	outline: none;
	background: transparent;
	-webkit-appearance: none; /* 禁用默认样式 */
}

/* 禁用滚轮事件 */
.amount-input {
	overscroll-behavior: none;
	overflow: hidden;
}

/* 禁用上下箭头 */
.amount-input::-webkit-inner-spin-button,
.amount-input::-webkit-outer-spin-button {
	-webkit-appearance: none;
	margin: 0;
}

/* 禁用滚动 */
.amount-input::-webkit-scrollbar {
	display: none;
}

/* 输入框获得焦点时的样式 */
.amount-input:focus {
	border-bottom: 2rpx solid #7F7FD5;
}

.note-input {
		display: flex;
		align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.note-input image {
	width: 40rpx;
	height: 40rpx;
	margin-right: 20rpx;
}

.note-input input {
	flex: 1;
	font-size: 28rpx;
}

.date-picker {
		display: flex;
		align-items: center;
	padding: 20rpx 0;
}

.date-picker image {
	width: 40rpx;
	height: 40rpx;
	margin-right: 20rpx;
}

/* 数字键盘样式 */
.keypad {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #f5f7fa;
	padding: 20rpx;
}

.keypad-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10rpx;
}

.key-item {
	flex: 1;
	height: 100rpx;
	margin: 5rpx;
	border-radius: 10rpx;
	background: #fff;
		display: flex;
	align-items: center;
		justify-content: center;
	font-size: 32rpx;
	box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
}

.key-item.operator {
	background: #f0f3f9;
}

.key-item.enter {
	background: linear-gradient(135deg, #7F7FD5, #86A8E7);
	color: #fff;
}

.key-item.delete image {
	width: 40rpx;
	height: 40rpx;
}

/* 添加分类弹窗样式 */
.add-category-popup {
	background: #fff;
	border-radius: 20rpx;
	width: 600rpx;
	padding: 30rpx;
}

.popup-header {
	text-align: center;
	font-size: 32rpx;
	font-weight: 500;
	margin-bottom: 30rpx;
}

.category-input {
	border: 1rpx solid #eee;
	border-radius: 8rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	font-size: 28rpx;
}

.icon-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 20rpx;
	padding: 20rpx 0;
}

.icon-item {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background: #f5f7fa;
	display: flex;
		align-items: center;
	justify-content: center;
	margin: 0 auto;
	border: 2rpx solid transparent;
	transition: all 0.3s;
}

.icon-item.selected {
	border-color: #7F7FD5;
	background: rgba(127, 127, 213, 0.1);
}

.icon-item image {
	width: 44rpx;
	height: 44rpx;
}

.popup-footer {
	display: flex;
	justify-content: space-between;
	margin-top: 30rpx;
}

.popup-footer button {
	margin: 0;
	width: 45%;
	font-size: 28rpx;
}

.cancel-btn {
	background: #f5f7fa;
	color: #666;
}

.confirm-btn {
	background: linear-gradient(135deg, #7F7FD5, #86A8E7);
}

/* 添加日期按钮样式 */
.key-item.date {
	background: #f8f9fa;
	color: #666;
	}

	.popup-view {
	background: #fff;
	border-radius: 20rpx 20rpx 0 0;
				overflow: hidden;
	}

	.popup-view-header {
		display: flex;
		justify-content: space-between;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #eee;
}

.popup-view-cancel,
.popup-view-confirm {
	font-size: 28rpx;
	padding: 10rpx;
}

.popup-view-cancel {
	color: #666;
}

.popup-view-confirm {
	color: #7F7FD5;
}

.picker-view {
	width: 750rpx;
	height: 500rpx;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}
</style>